<?php

namespace app\command\command;

use PDO;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Exception;

class ImportSql extends Command
{

    protected function configure()
    {
        $this->setName('importSql')
            ->setDescription('import mysql sql')
            ->addArgument('table');

    }

    protected function execute(Input $input, Output $output)
    {
        $table = $input->getArgument('table');

        $config = Config::get('database');

        $sql_file = ROOT_PATH . 'app/command/database/' . $table . '.sql';

        $sql = file_get_contents($sql_file);
        $sql_arr = explode('############# IMPORT END #############', $sql);

        // 获取将要执行的sql
        $exec_sql = $sql_arr[count($sql_arr) - 1];
        if(empty($exec_sql)){
            echo '暂无需要执行的SQL';
            return;
        }

        $remove_exec_sql = str_replace($exec_sql, '', $sql);

        // 先尝试能否自动创建数据库
        try {
            $mysqlHostname = $config['hostname'];
            $mysqlHostport = $config['hostport'];
            $mysqlUsername = $config['username'];
            $mysqlPassword = $config['password'];
            $pdo = new PDO("{$config['type']}:host={$mysqlHostname}" . ($mysqlHostport ? ";port={$mysqlHostport}" : ''), $mysqlUsername, $mysqlPassword);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->query($exec_sql);

            $import_start = '############# IMPORT START #############';
            $import_date = '############# ' . date("Y-m-d H:i:s") . ' #############';
            $import_end = '############# IMPORT END #############';
            $replace_exec_sql = PHP_EOL . PHP_EOL . $import_start . PHP_EOL . $import_date . PHP_EOL . $exec_sql . PHP_EOL . $import_end;

            $new_sql = $remove_exec_sql . $replace_exec_sql;
            file_put_contents($sql_file, $new_sql);

            echo 'SUCCESS';
        } catch (\PDOException $e) {
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 检测环境
     */
    protected function checkenv()
    {
        // 检测目录是否存在
        $checkDirs = [
            'thinkphp',
            'vendor',
            'public' . DS . 'assets' . DS . 'libs'
        ];

        //数据库配置文件
        $dbConfigFile = APP_PATH . 'database.php';

        if (version_compare(PHP_VERSION, '7.1.0', '<')) {
            throw new Exception(__("The current version %s is too low, please use PHP 7.1 or higher", PHP_VERSION));
        }
        if (!extension_loaded("PDO")) {
            throw new Exception(__("PDO is not currently installed and cannot be installed"));
        }
        if (!is_really_writable($dbConfigFile)) {
            throw new Exception(__('The current permissions are insufficient to write the configuration file application/database.php'));
        }
        foreach ($checkDirs as $k => $v) {
            if (!is_dir(ROOT_PATH . $v)) {
                throw new Exception(__('Please go to the official website to download the full package or resource package and try to install'));
                break;
            }
        }
        return true;
    }
}